package com.lql.lqlreader.service.converter

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.lql.lqlreader.service.exception.HttpResultException
import com.lql.lqlreader.service.entity.HttpErrorResponseEntity
import com.lql.lqlreader.service.entity.HttpResultEntity
import okhttp3.ResponseBody
import retrofit2.Converter
import timber.log.Timber
import java.lang.reflect.Type

class MyGsonConverter<T>(val gson: Gson, val type: Type) : Converter<ResponseBody, T> {
    private lateinit var httpResult: HttpResultEntity<T>

    override fun convert(responseBody: ResponseBody): T? {
        val responseString = responseBody.string()
        Timber.e(responseString)

        if (TextUtils.isEmpty(responseString)) {
            val errorResponse = HttpErrorResponseEntity(-200, "The result of the request is returned as null")
            val resultException = HttpResultException(errorResponse.errorCode, errorResponse.errorMsg)
            Timber.e("this ResultException msg is %s", "request result is null")
            Timber.d("The responseStr is %s", responseString)
            throw resultException
        }

        try {
            httpResult = gson.fromJson(responseString, HttpResultEntity::class.java) as HttpResultEntity<T>
        } catch (e: JsonSyntaxException) {
            val resultException = HttpResultException(-201, "Json conversion exception")
            Timber.e("this JsonSyntaxException msg is %s", e.localizedMessage)
            Timber.d("The responseString is %s", responseString)
            throw resultException
        }

        if (httpResult.errorCode == 0) {
            try {
                return gson.fromJson(responseString, type)
            } catch (e: JsonSyntaxException) {
                Timber.e("this JsonSyntaxException msg is %s", e.message)
                Timber.d("The responseString is %s", responseString)
                val errorResponse = HttpErrorResponseEntity(-202, "Json conversion exception")
                throw HttpResultException(errorResponse.errorCode, errorResponse.errorMsg)
            }
        } else {
            try {
                Timber.e("this ResultException msg is %s", "json convert fail")
                Timber.d("The responseString is %s", responseString)
                val errorResponse = gson.fromJson(responseString, HttpErrorResponseEntity::class.java)
                throw HttpResultException(errorResponse.errorCode, errorResponse.errorMsg)
            } catch (e: JsonSyntaxException) {
                Timber.e("this JsonSyntaxException msg is %s", e.message)
                Timber.d("The responseString is %s", responseString)
                val errorResponse = HttpErrorResponseEntity(-203, "Json conversion exception")
                throw HttpResultException(errorResponse.errorCode, errorResponse.errorMsg)
            }
        }
    }
}